package cn.iotnova.rtc;

//AndroidStudio Build Output乱码解决
//https://www.jianshu.com/p/c836adec5574

public class WebsocketSignal implements ISignalcallback {
    Rtcclient rtcclient = new Rtcclient();

    public void Init(ISignalcallback callback) {
        signalcallback = callback;
        new Thread(new Runnable() {
            @Override
            public void run() {
                String conn_id;
                while (auto_reconnect && !isclosed) {
                    try {
                        //conn_id = Rtcclient.ClientSignalInit("114.117.194.15", "8888", "clientws", "zyh", "123", "1");
                        conn_id = rtcclient.ClientSignalInit("192.168.1.2", "7000", "clientws", "zyh", "123", "1");
                        connId = conn_id;
                        if (conn_id.equals("")) {
                            Thread.sleep(1000);
                            continue;
                        }
                        isconnected = true;
                        rtcclient.setCallback(conn_id, WebsocketSignal.this);

                        rtcclient.ClientReadData(conn_id);
                        _close();
                        Thread.sleep(1000);
                    } catch (Exception e) {

                    }
                }
            }
        }).start();
    }

    //WebrtcPeer activity;

    private String connId;
    private boolean isclosed = false;
    boolean auto_reconnect = true;

    public void setId(String _id) {
        connId = _id;
    }


    ///////////////////////////////////////////////////////////////////////////////////
    public void sendMessage(int type, String msg) {
        rtcclient.ClientSendData(connId, type, msg);
        /*
        new Thread(new Runnable() {
            @Override
            public void run() {
                Websocket.ClientSendData(connId, msg);
            }
        }).start();
         */
    }

    private boolean isconnected = false;

    private void _close() {
        rtcclient.Close(connId);
    }

    public void Close() {
        isclosed = true;
        rtcclient.Close(connId);
    }

    ISignalcallback signalcallback;

    @Override
    public void SignalRecv(int type, String dat) {
        //activity.handleMessage(type, dat);
        signalcallback.SignalRecv(type, dat);
    }
}
